<script>
import EventBus from '@/utils/bus'
// 动态销毁
let that
const removeVnode = (targetKey) => {
  if (that.$store.getters.multiTab) {
    const vnode = that.$children.find((e) => e.$vnode.key === targetKey)
    if (vnode) {
      vnode.removeKeepAlive()
    }
  }
}
EventBus.$on('removeTab', (targetKey) => {
  removeVnode(targetKey)
})
// 刷新
EventBus.$on('reload', (targetKey) => {
  that.isReload = true
  that.$nextTick(() => {
    that.isReload = false
  })
  removeVnode(targetKey)
})

export default {
  name: 'RouteView',
  props: {
    keepAlive: {
      type: Boolean,
      default: true
    }
  },
  data () {
    return {
      isReload: false
    }
  },
  render () {
    that = this
    const {
      $route: { meta, fullPath },
      $store: { getters }
    } = this
    const len = 20
    const inKeep = <keep-alive include={fullPath} max={len}>{this.isReload ? '' : <router-view key={fullPath} />}</keep-alive>
    const notKeep = <router-view />
    // 这里增加了 multiTab 的判断，当开启了 multiTab 时
    // 应当全部组件皆缓存，否则会导致切换页面后页面还原成原始状态
    // 若确实不需要，可改为 return meta.keepAlive ? inKeep : notKeep
    if (!getters.multiTab && !meta.keepAlive) {
      return notKeep
    }
    return this.keepAlive || getters.multiTab || meta.keepAlive ? inKeep : notKeep
  }
}
</script>
